﻿using UnityEngine;
using UniBrickCommon;
using UniBrickCommon.Packets;
using Lidgren.Network;
using UnityStandardAssets.Cameras;
using System.Collections;

public class PlayerController : MonoBehaviour
{
    public float Speed = 10.0f;
    public float TurnSpeed = 80.0f;

    public Vector3 NetworkPosition;
    public Quaternion NetworkRotation;

    private Animator _animator;

    void Start()
    {
        _animator = GetComponent<Animator>();
        StartCoroutine("SendUpdate");
        NetworkPosition = transform.position;
        NetworkRotation = transform.rotation;
    }

    void Update()
    {
        var h = Input.GetAxis("Horizontal");
        var v = Input.GetAxis("Vertical");
        var jump = Input.GetButton("Jump");

        _animator.SetBool("Walk", v > 0);
        _animator.SetBool("Reverse", v < 0);
        _animator.SetBool("Turn", h != 0);
        _animator.SetBool("Jump", jump);

        var rightClick = Input.GetMouseButton(1);

        //if (rightClick)
        //{
        //    GameObject.Find("Camera").transform.LookAt(transform);
        //    GameObject.Find("Camera").transform.Translate(Vector3.right * Input.GetAxis("Mouse X"));
        //}

        GameObject.Find("Camera").GetComponent<AutoCam>().m_TurnSpeed = rightClick ? 0 : 1;

        transform.Translate((v < 0 ? v / 2 : v) * Speed * (_animator.GetCurrentAnimatorStateInfo(0).IsName("Jumping") ? 1.5f : 1.0f) * Vector3.forward * Time.deltaTime);
        transform.Rotate(Vector3.up * h * TurnSpeed * Time.deltaTime);
    }

    IEnumerator SendUpdate()
    {
        while (true)
        {
            if (Vector3.Distance(NetworkPosition, transform.position) > 1 || Mathf.Abs(NetworkRotation.eulerAngles.y - transform.rotation.eulerAngles.y) > 1)
            {
                NetworkPosition = transform.position;
                NetworkRotation = transform.rotation;

                UniBrickClient.Instance.SendPacket(UniBrickPacketCode.UpdateRequest,
                    new UpdatePacket.Request(NetworkPosition.ToVectorString(),
                        NetworkRotation.ToQuaternionString()),
                        NetDeliveryMethod.UnreliableSequenced);
            }
            yield return new WaitForSeconds(1 / 20);
        }
    }
}